#include "mainpage.h"
#include "ui_mainpage.h"

#include <QPainter>

Mainpage::Mainpage(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Mainpage)
{
    ui->setupUi(this);

    //设置文本框名称
     this->setWindowTitle(QStringLiteral("智慧交通系统"));
    // 访问到资源
    QIcon icon(":/icon/Image/mao.png");
    // 设置图标
    this->setWindowIcon(icon);

    ui->page_map->installEventFilter(this);

    initRoad();
    initCross();
   // initCar();模拟随机的20辆车
    initNet();


    connect(&ns,&NetServer::signal_addCar,this,&Mainpage::slot_addCar);
    connect(&ns,&NetServer::signal_updateCar,this,&Mainpage::slot_updateCar);
    connect(&ns,&NetServer::signal_getCrossState,this,&Mainpage::slot_getCrossState);
}

Mainpage::~Mainpage()
{
    delete ui;
}


void Mainpage::slot_getCrossState(const int &road_id, bool &ok)
{
    ok=true;//道路没有红绿灯
    for(auto cross:list_cross){
        if(cross.road_sl.contains(&list_road[road_id])){
            //这条路通向该路口
            SignalLamp *sl= cross.road_sl.value(&list_road[road_id]);
            if(sl->color==Qt::green){
                ok= true;
            }else{
                ok=false;
           }
        }
    }
}

//项目过滤器
bool Mainpage::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == ui->page_map) {
             if (event->type() == QEvent::Paint) {
                // QPainter painter(ui->page_map);
                 QPainter painter;
                 QImage img(":/icon/Image/RoadMap.png");
                 painter.begin(&img);

                 //画道路

                 painter.save();
                 if(showRoad){
                 QPen pen;
                // pen.setColor(QColor(0,255,0));
                 pen.setColor(Qt::green);
                 pen.setWidth(3);
                 painter.setPen(pen);
                 for(auto item:list_road){
                     painter.drawLine(item.start,item.end);
                 }
                 painter.restore();
}

                 //画路口
                 if(showCross){

                 for(auto item:list_cross){
                     painter.drawRect(item.local);
                     //画红绿灯
                     for(auto key:item.road_sl.keys()){
                         painter.save();
                         SignalLamp *sl = item.road_sl.value(key);

                         painter.setBrush(QBrush(QColor(sl->color)));//给灯填充颜色
                         painter.drawEllipse(key->end,8,8);
                         //画红绿灯上的数字，偏移
                         painter.drawText(key->end-QPoint(5,-4),
                                          QString::number(sl->count));
                         //倒计时与变灯
                         // 倒计时逻辑
                                                 if (sl->count > 0) {
                                                     sl->count--;
                                                 } else {
                                                     // 倒计时结束，改变信号灯颜色
                                                     if (sl->color == Qt::red) {
                                                         sl->color = Qt::green;
                                                         sl->count = 20; // 假设绿灯持续时间为5秒
                                                     } else {
                                                         sl->color = Qt::red;
                                                         sl->count = 20; // 假设红灯持续时间为10秒
                                                     }
                                                 }
                         painter.restore();
                        // painter.drawEllipse(key->end,5,5);
                     }
                 }
}

                 //画小车
                 if(showCar){
                         QImage carImage(":/icon/Image/car.png");
                         for(auto item:list_car){
                             if(item.road==nullptr)continue;//判断道路是不是空指针
                             QPoint pos=item.road->start-(item.road->start-item.road->end)*item.duration;
                             painter.drawImage(QRect(pos-QPoint(15,15),QSize(30,30)),
                                               carImage,carImage.rect());
                             drawCarId(painter, pos, item.id); // 在小车上方绘制 ID


                         }
}
                 painter.end();

                 painter.begin(ui->page_map);
                 painter.drawImage(ui->page_map->rect(),img,img.rect());
                 painter.end();

                 return true;
             } else {
                 return false;
             }
         } else {
             // pass the event on to the parent class
             return QWidget::eventFilter(obj, event);
    }
}

//小车头顶ID
void Mainpage::drawCarId(QPainter &painter, QPoint pos, int id)
{

    painter.setPen(Qt::white);//画笔颜色
        painter.setFont(QFont("Arial", 20, QFont::Bold));//字体
        painter.drawText(pos.x()-55, pos.y() - 20, QString("晋A·0%1").arg(id));//文本
}

void Mainpage::on_psbt_exit_clicked()
{
    this->close();
}

void Mainpage::slot_addCar(const int &id)
{

    Car car(id,nullptr);
    list_car.append(car);
    ui->cmx_carId->addItem(QString::number(id));
}

void Mainpage::slot_updateCar(const int &id, const int &road_id, const float &duration)
{
    for(int i=0;i<list_car.count();i++)
    {
        if(list_car[i].id==id){
            list_car[i].road=&list_road[road_id];
            list_car[i].duration=duration;
        }
    }
    ui->page_map->update();//会更新整个界面
}


void Mainpage::initRoad()
{
    int id=0;

            Road road1(id++,QPoint(85,34),QPoint(756,34));
            list_road.append(road1);
            Road road2(id++,QPoint(756,65),QPoint(85,65));
            list_road.append(road2);

            Road road3(id++,QPoint(31,86),QPoint(31,332));
            list_road.append(road3);
            Road road4(id++,QPoint(62,332),QPoint(62,86));
            list_road.append(road4);

            Road road5(id++,QPoint(778,86),QPoint(778,332));
            list_road.append(road5);
            Road road6(id++,QPoint(810,332),QPoint(810,86));
            list_road.append(road6);

            Road road7(id++,QPoint(756,349),QPoint(85,349));
            list_road.append(road7);
            Road road8(id++,QPoint(85,380),QPoint(756,380));
            list_road.append(road8);

            Road road9(id++,QPoint(31,404),QPoint(31,655));
            list_road.append(road9);
            Road road10(id++,QPoint(62,655),QPoint(62,404));
            list_road.append(road10);

            Road road11(id++,QPoint(778,404),QPoint(778,655));
            list_road.append(road11);
            Road road12(id++,QPoint(810,655),QPoint(810,404));
            list_road.append(road12);

            Road road13(id++,QPoint(756,675),QPoint(85,675));
            list_road.append(road13);
            Road road14(id++,QPoint(85,706),QPoint(756,706));
            list_road.append(road14);
}

//此处设置路口数据  ↓↓↓
void Mainpage::initCross(){
    if(list_road.count()<14)return;
    int id = 0;
    Cross cross1(id++);
    SignalLamp *sl1 =new SignalLamp;
    SignalLamp *sl2 =new SignalLamp;

    sl1->color=Qt::red;
    sl1->count=20;
    sl2->color=Qt::green;
    sl2->count=20;

    cross1.list_sl.append(sl1);
    cross1.list_sl.append(sl2);//信号灯和路口联合起来
    cross1.N_exit=&list_road[3];//如果不做安全检查 此处会报错
    cross1.N_entrance=&list_road[2];
    cross1.E_exit=&list_road[7];
    cross1.E_entrance=&list_road[6];
    cross1.S_exit=&list_road[8];
    cross1.S_entrance=&list_road[9];
    cross1.W_exit=nullptr;
    cross1.W_entrance=nullptr;

    cross1.road_sl.insert(cross1.S_entrance,cross1.list_sl[0]);
    cross1.road_sl.insert(cross1.N_entrance,cross1.list_sl[0]);
    cross1.road_sl.insert(cross1.E_entrance,cross1.list_sl[1]);
    cross1.local=QRect(cross1.N_entrance->end-QPoint(8,-8),
                       cross1.S_entrance->end-QPoint(-8,8));
    list_cross.append(cross1);

    Cross cross2(id++);
    SignalLamp *sl3=new SignalLamp;
    SignalLamp *sl4=new SignalLamp;

    sl3->color=Qt::red;
    sl3->count=20;
    sl4->color=Qt::green;
    sl4->count=20;

    cross2.list_sl.append(sl3);
    cross2.list_sl.append(sl4);//信号灯和路口联合起来
    cross2.N_exit=&list_road[5];//如果不做安全检查 此处会报错
    cross2.N_entrance=&list_road[4];
    cross2.E_exit=nullptr;
    cross2.E_entrance=nullptr;
    cross2.S_exit=&list_road[10];
    cross2.S_entrance=&list_road[11];
    cross2.W_exit=&list_road[6];
    cross2.W_entrance=&list_road[7];

    cross2.road_sl.insert(cross2.S_entrance,cross2.list_sl[0]);
    cross2.road_sl.insert(cross2.N_entrance,cross2.list_sl[0]);
    cross2.road_sl.insert(cross2.W_entrance,cross2.list_sl[1]);
    cross2.local=QRect(cross2.N_entrance->end-QPoint(6,-6),
                       cross2.S_entrance->end-QPoint(-6,6));
    list_cross.append(cross2);

}

void Mainpage::initCar()
{
    srand(time(nullptr));
    int id=0;
    //Car car(id++,&list_road[0],1);
    for(int i=0;i<20;i++){
        Car car(id++,&list_road[rand()%14],(rand()%100/100.0f));
       list_car.append(car);
    }
}

void Mainpage::initNet()
{
    ns.startListen();//开始监听
}

void Mainpage::on_psbt_lkkz_clicked()
{
    ui->stackedWidget->setCurrentWidget(ui->pagechange);
}

void Mainpage::on_psbt_dwxx_clicked()
{
    ui->stackedWidget->setCurrentWidget(ui->page_map);
    showRoad=showCross=false;
    showCar=true;
    ui->page_map->update();
}
//车辆控制
void Mainpage::on_psbt_clkzxx_clicked()
{
    ui->stackedWidget->setCurrentWidget(ui->page_car);
}


void Mainpage::on_psbt_zhxx_clicked()
{
    ui->stackedWidget->setCurrentWidget(ui->page_map);
    showCar=showRoad=showCross=true;
    ui->page_map->update();
}

//熄火
void Mainpage::on_start_clicked()
{
    //车辆启动
    int carId=ui->cmx_carId->currentText().toInt();
    ns.sendStartToCar(carId);
}

void Mainpage::on_stop_clicked()
{
    //车辆熄火
    int carId=ui->cmx_carId->currentText().toInt();
    ns.sendStopToCar(carId);
}

void Mainpage::SendGetCrossState()
{

}
//路口信息
void Mainpage::on_psbt_lkxx_clicked()
{
    ui->stackedWidget->setCurrentWidget(ui->page_cross);
    // 发送请求到服务器
        bool ok;
        int road_id = 0;
        emit ns.signal_getCrossState(road_id, ok);

        // 接收服务器返回的信息
        connect(&ns, &NetServer::signal_getCrossState, this, [=](const int &road_id, bool &state) {
            // 将服务器返回的信息显示在 ui->label 上
            ui->label_cross->setText(QString("路口 %1 的状态：%2").arg(road_id).arg(state? "可通行" : "不可通行"));
        });

}


void Mainpage::on_psbt_dlxx_clicked()
{
    ui->stackedWidget->setCurrentWidget(ui->page_map);
    showCross =showCar = false;
    showRoad = true;
    ui->page_map->update();
}
